package org.kjtc.web;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2017-12-14.
 */
public class Tools {
    public  static  String convertDate(Date date) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        int weekOfYear = cl.get(Calendar.WEEK_OF_YEAR);
        return date2Str(date,"MM") + "月" + String.valueOf(weekOfYear) + "周";
    }

    public static String date2Str(Date date, String formate) {
        if(date!=null){
            SimpleDateFormat sdf = new SimpleDateFormat(formate);
            return sdf.format(date);
        }else{
            return "";
        }
    }

    public static Date str2DTTM(String str) {
        if(str.length() == 10) {
            str = str + " 00:00:00";
        } else if(str.length() == 13) {
            str = str + ":00:00";
        } else if (str.length() == 16) {
            str = str + ":00";
        }
        if(notEmpty(str)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                return sdf.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        }else{
            return null;
        }
    }

    public static boolean notEmpty(String s){
        return s!=null && !"".equals(s) && !"null".equals(s);
    }

    public static JSONObject requestHttpUrl(String url, Map<String, Object> requestMap) throws Exception{
        System.out.println("请求服务器开始：" + url);
        HttpURLConnection httpURLConnection = null;
        JSONObject json = null;

        try {
            URL realUrl = new URL(URLDecoder.decode(url, "UTF-8"));
            if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
            }

            httpURLConnection = (HttpURLConnection)realUrl.openConnection();
            realUrl = null;
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.setReadTimeout(30000);
            String jsonResult = "";
            if (requestMap != null) {
                OutputStreamWriter out = new OutputStreamWriter(httpURLConnection.getOutputStream(), "utf-8");
                jsonResult = JSONObject.fromObject(requestMap).toString();
                System.out.println("连接服务器并发送请求数据：" + jsonResult);
                out.write(jsonResult);
                out.flush();
                out.close();
                out = null;
            }

            int responseCode = httpURLConnection.getResponseCode();
            if (200 == responseCode) {
                System.out.println("连接服务器成功");
                StringBuilder strBuilder = new StringBuilder();
                String readLine = null;
                InputStreamReader in = new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(in);

                while((readLine = br.readLine()) != null) {
                    strBuilder.append(readLine);
                }

                br.close();
                in.close();
                readLine = null;
                br = null;
                in = null;
                if (strBuilder != null) {
                    json = JSONObject.fromObject(strBuilder.toString());
                    System.out.println("服务器返回结果：" + json.toString());
                }

                strBuilder = null;
                httpURLConnection = null;
            } else if (408 == responseCode) {
                System.out.println("请求服务器超时");
            }
        } catch (IOException var14) {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

            var14.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

        }
        System.out.println("请求服务器结束");
        return json;
    }
    public static void writeFile(String fileP, String content, boolean isAbsolutePath)throws Exception{
        String filePath = "";
        if (isAbsolutePath)
        {
            filePath = fileP.trim();
            File file = new File(filePath);
            if ((file != null) && (!file.exists()))
            {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
        }
        else
        {
            filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../";
            filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
            if (filePath.indexOf(":") != 1) {
                filePath = File.separator + filePath;
            }
        }
        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
        BufferedWriter writer = new BufferedWriter(write);
        writer.write(content);
        writer.close();
    }

}
